package com.ns.core.utils.http;

import com.ns.core.utils.sg.ResultError;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * 对外请求工具
 *
 * @author lw
 * @since 2024-11-11
 */
public class JdkHttpUtil {

    /**
     * 发送GET 请求
     *
     * @param uri uri
     */
    public static String sendGet(String uri) {
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response;
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(uri))
                    .GET()
                    .build();
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (Exception e) {
            throw new ResultError("请求失败，请稍后重试！");
        }
        return response.body();
    }

    /**
     * 发送POST请求
     * sendPostRequest(" http : / / example.com ", " param1 = value1 & param2 = value2 ");
     *
     * @param uri  uri
     * @param body 请求体
     */
    public static String sendPost(String uri, String body) {
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response;
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(uri))
                    .POST(HttpRequest.BodyPublishers.ofString(body))
                    .build();

            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (Exception e) {
            throw new ResultError("请求失败，请稍后重试！");
        }
        return response.body();
    }
}